//
//  LGCLastViewController.m
//  XiMaLaYa
//
//  Created by dllo on 15/11/16.
//  Copyright © 2015年 L-G. All rights reserved.
//

#import "LGCLastViewController.h"
#import "GetConnection.h"
#import <AFNetworking.h>
#import "TrackModel.h"
#import <MBProgressHUD.h>
#import "Song.h"
#import "CoreDataManager.h"
#import "BaseView.h"
#import "SongListTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "SongsModel.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width / 375
#define HEIGHT [UIScreen mainScreen].bounds.size.height / 667


@interface LGCLastViewController ()<STKAudioPlayerDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, retain)CoreDataManager *coreDataManager;

@property (nonatomic, retain)NSURLConnection *connection;

@property (nonatomic, assign)float current;

@property (nonatomic, assign)float total;

@property (nonatomic, retain)NSFileHandle *fileHandle;

@property (nonatomic, retain)BaseView *view_song_list;

@property (nonatomic, retain)UITableView *tableview_song_list;

@property (nonatomic, retain) UIImageView *image;



@end

@implementation LGCLastViewController
- (void)dealloc
{
    [_connection release];
    [_fileHandle release];
    [_tableview_song_list release];
    [_array_current release];
    [_arrayList release];
    [_view_song_list release];
    [_labelCurrent release];
    [_labelDuration release];
    [_labelTitle release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arrayList = [NSMutableArray array];
         self.tempArray = [NSMutableArray array];
        

    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    self.array_current = [NSMutableArray array];
    if ([self.strTitle isEqualToString:@""]) {
        self.labelTitle.text = @"卢秀斌";
        self.playUrl = @"123";
    }
    self.labelTitle.text = self.strTitle;
    self.coreDataManager = [CoreDataManager shareManager];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Song"];
    request.predicate = [NSPredicate predicateWithFormat:@"songName = %@",self.labelTitle.text];
    NSArray *arrayd = [self.coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
//    if (arrayd.count > 0) {
//    [self.btn_save setImage:[UIImage imageNamed:@"iconfont-shoucangyishoucang"] forState:UIControlStateNormal];
//    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:self.labelTitle.text];
//        }else
//        {
//    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:self.labelTitle.text];
//    [self.btn_save setImage:[UIImage imageNamed:@"iconfont-shoucangweishoucang-2"] forState:UIControlStateNormal];
//        }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSLog(@"!!!!%ld",self.array_current.count);
    
    [self addMyTarget:self Action:@selector(Action)];

    [self createSubviews];
    /***************** player创建  *****************/
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){
        .flushQueueOnSeek = YES,
        .enableVolumeMixer = YES
    }];
    self.player.volume = 1.0;
    self.player.delegate = self;
   [self playMusic:self.playUrl];
    /*****************            *****************/
    [self create_song_list];
}
- (void)Action
{
    self.view_song_list.hidden = YES;
    self.btn_list.selected = NO;
}
- (void)createSubviews
{
    UIImageView *imagCover = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    imagCover.image = [UIImage imageNamed:@"backgroundImage5.jpg"];
    
//    [imagCover sd_setImageWithURL:[NSURL URLWithString:_Pic]];
//    imagCover.alpha = 0.5;
    
    [self.view addSubview:imagCover];
    
   self.image = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - WIDTH * 60, HEIGHT * 250, WIDTH * 120, HEIGHT * 120)];
    self.image.layer.cornerRadius = WIDTH * 60;
    self.image.clipsToBounds = YES;
    
    [self.view addSubview:self.image];
    [self.image release];
    
    self.labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(55 * WIDTH, 35 * HEIGHT, self.view.frame.size.width - 160 * WIDTH, 20 * HEIGHT)];
    self.labelTitle.text = @"卢秀斌";
    self.labelTitle.font = [UIFont systemFontOfSize:19];
    self.labelTitle.textColor = [UIColor whiteColor];
    [self.view addSubview:self.labelTitle];
    
    // 返回
    UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    btnBack.frame = CGRectMake(15 * WIDTH, 23 * HEIGHT, 35 * WIDTH, 35 * HEIGHT);
    [btnBack setImage:[UIImage imageNamed:@"back@2x副本"] forState:UIControlStateNormal];
    [btnBack addTarget:self action:@selector(btnBackAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnBack];
    // 播放和暂停
    self.btnCurrent = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnCurrent.frame = CGRectMake((self.view.frame.size.width - 35 * WIDTH) / 2, self.view.frame.size.height - 100 * HEIGHT, 30 * WIDTH, 30 * HEIGHT);
    [self.btnCurrent setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
    [self.btnCurrent addTarget:self action:@selector(btnCurrentAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnCurrent];
    
    // 下一曲
    self.btnNext = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnNext.frame = CGRectMake(self.view.frame.size.width -  120 * WIDTH, self.view.frame.size.height - 95 * HEIGHT, 20 * WIDTH, 20 * HEIGHT);
    [self.btnNext setImage:[UIImage imageNamed:@"xiayiqu"] forState:UIControlStateNormal];
    [self.btnNext addTarget:self action:@selector(btnNextAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnNext];
    
    // 上一曲
    self.btnUp = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnUp.frame = CGRectMake(90 * WIDTH, self.view.frame.size.height - 95 * HEIGHT, 20 * WIDTH, 20 * HEIGHT);
    [self.btnUp setImage:[UIImage imageNamed:@"shangyiqu"] forState:UIControlStateNormal];
    [self.btnUp addTarget:self action:@selector(btnUpAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnUp];
    
    // 随机
    self.btn_sj = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btn_sj.frame = CGRectMake(30 * WIDTH, self.view.frame.size.height - 95 * HEIGHT, 20 * WIDTH, 20 * HEIGHT);
    [self.btn_sj setImage:[UIImage imageNamed:@"suijibofang"] forState:UIControlStateNormal];
    [self.btn_sj setImage:[UIImage imageNamed:@"suijibofanglight"] forState:UIControlStateHighlighted];
    [self.btn_sj addTarget: self action:@selector(btn_sjAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn_sj];
    
    // 进度条
    UIImage *thumbImage = [UIImage imageNamed:@"iconfont-huakuai-2"];
    self.currentSlider = [[UISlider alloc] initWithFrame:CGRectMake(60 * WIDTH,self.view.frame.size.height - 150 * HEIGHT, self.view.frame.size.width - 120 * WIDTH, 7 * HEIGHT)];
    [self.currentSlider setThumbImage:thumbImage forState:UIControlStateHighlighted];
    [self.currentSlider setThumbImage:thumbImage forState:UIControlStateNormal];
       [self.currentSlider addTarget:self action:@selector(currentSliderAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.currentSlider];
    [_currentSlider release];
    
    // 记录当前时间
    self.labelCurrent = [[UILabel alloc] initWithFrame:CGRectMake(10 * WIDTH,self.view.frame.size.height - 153 * HEIGHT, 40 * WIDTH, 15 * HEIGHT)];
    self.labelCurrent.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:self.labelCurrent];
    [_labelCurrent release];
    
    // 记录总时长
    self.labelDuration = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 45 * WIDTH, self.view.frame.size.height - 153 * HEIGHT, 40 * WIDTH, 15 * HEIGHT)];
    self.labelDuration.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:self.labelDuration];
    [_labelDuration release];
    
    // 列表
    self.btn_list = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btn_list.frame = CGRectMake(self.view.frame.size.width - 50 * WIDTH, self.view.frame.size.height - 95 * HEIGHT, 20 * WIDTH, 20 * HEIGHT);
    [self.btn_list setImage:[UIImage imageNamed:@"iconfont-liebiao"] forState:UIControlStateNormal];
    [self.btn_list setImage:[UIImage imageNamed:@"iconfont-liebiaolight"] forState:UIControlStateHighlighted];
    [self.btn_list addTarget:self action:@selector(btn_listAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn_list];
    
    // 下载
    self.btn_download = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btn_download.frame = CGRectMake(self.view.frame.size.width - 100 * WIDTH, 30 * HEIGHT, 25 * WIDTH, 25 * HEIGHT);
    [self.btn_download setImage:[UIImage imageNamed:@"iconfont-download"] forState:UIControlStateNormal];
    [self.btn_download setImage:[UIImage imageNamed:@"iconfont-xiazai"] forState:UIControlStateHighlighted];
    [self.btn_download addTarget:self action:@selector(btn_downloadAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn_download];
    
    // 收藏
    self.btn_save = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btn_save.frame = CGRectMake(self.view.frame.size.width - 55 * WIDTH, 28 * HEIGHT, 30 * WIDTH, 30 * HEIGHT);
    [self.btn_save setImage:[UIImage imageNamed:@"iconfont-shoucangweishoucang-2"] forState:UIControlStateNormal];
    [self.btn_save addTarget:self action:@selector(btn_saveAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn_save];
}

- (void)create_song_list
{
    self.view_song_list = [[BaseView alloc] initWithFrame:CGRectMake(100 * WIDTH, 220 * HEIGHT, 250 * WIDTH, 330 * HEIGHT)];
    self.view_song_list.backgroundColor = [UIColor grayColor];
    self.view_song_list.alpha = 0.8;
    [self.view addSubview:self.view_song_list];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20 * WIDTH, 0, 100 * WIDTH, 30 * HEIGHT)];
    label.text = @"当前队列";
    label.textColor = [UIColor whiteColor];
    [self.view_song_list addSubview:label];
    
    self.tableview_song_list = [[UITableView alloc] initWithFrame:CGRectMake(0,30 * HEIGHT, 250 * WIDTH, 280 * HEIGHT) style:UITableViewStylePlain];
    self.tableview_song_list.delegate = self;
    self.tableview_song_list.dataSource = self;
    [self.view_song_list addSubview:self.tableview_song_list];
    self.view_song_list.hidden = YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         self.view_song_list.hidden = YES;
        self.btn_list.selected = NO;
    });
    [self.player play:[self.array_current[indexPath.row] song_play_url]];
    
    self.labelTitle.text = [self.array_current [indexPath.row] song_name];
    _indexRow = indexPath.row;
}
- (void)playMusic:(NSString *)url
{
    [self.player play:url];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
    [self.btnCurrent setImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
}
- (void)track
{
    self.currentSlider.maximumValue = self.player.duration;// 歌曲总长度
    self.currentSlider.value = self.player.progress;// 歌曲当前进度
    
    // 当前时长进度progress
    NSInteger proMin = (NSInteger)self.player.progress / 60; // 当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60; // 当前分钟
    
    // duration 总长度
    NSInteger durMin = (NSInteger)self.player.duration / 60; // 总秒数
    NSInteger durSec = (NSInteger)self.player.duration % 60; // 总分钟数
    
    self.labelCurrent.text = [NSString stringWithFormat:@"%02ld:%02ld", proMin, proSec];
    self.labelDuration.text = [NSString stringWithFormat:@"%02ld:%02ld", durMin, durSec];
}
- (void)btn_sjAction:(id)sender
{
    
}
- (void)btn_listAction:(UIButton *)sender
{
    sender.selected = !sender.isSelected;
    if (sender.selected) {
        self.view_song_list.hidden = NO;
        [self.tableview_song_list reloadData];
    }else
    {
        self.view_song_list.hidden = YES;
    }
}
/*****************   *****************/
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array_current.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SongListTableViewCell *cell = [SongListTableViewCell songListTableViewCell:tableView];
    SongList *songList = self.array_current[indexPath.row];
    cell.songList = songList;
    cell.backgroundColor = [UIColor whiteColor];
    cell.textLabel.text = [NSString stringWithFormat:@"%02ld",indexPath.row + 1];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45 * WIDTH;
}
/***************** 收藏  *****************/

- (void)btn_saveAction:(UIButton *)sender
{
    // 提示用户
    MBProgressHUD *MBP = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    MBP.mode = MBProgressHUDModeText;
    [MBP show:YES];
    // btn 状态
    if (![[NSUserDefaults standardUserDefaults] boolForKey:self.labelTitle.text]) {
        [self.btn_save setImage:[UIImage imageNamed:@"iconfont-shoucangyishoucang"] forState:UIControlStateNormal];
            MBP.labelText = @"已收藏";
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBP removeFromSuperview];
        });
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:self.labelTitle.text];
        Song *song = [NSEntityDescription insertNewObjectForEntityForName:@"Song" inManagedObjectContext:self.coreDataManager.managedObjectContext];
        song.songName = self.labelTitle.text;
        song.songUser = @"123";
        [self.coreDataManager saveContext];
    }else
    {
        [self.btn_save setImage:[UIImage imageNamed:@"iconfont-shoucangweishoucang-2"] forState:UIControlStateNormal];
                MBP.labelText = @"已取消收藏";
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBP removeFromSuperview];
        });
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:self.labelTitle.text];
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Song"];
        NSArray *resultArray = [self.coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
        for (Song *song in resultArray) {
            [self.coreDataManager.managedObjectContext deleteObject:song];
        }
        [self.coreDataManager saveContext];        
    }
}
// 为slider赋值
- (void)currentSliderAction:(UISlider *)sender
{
    if (self.player) {
        [self.player seekToTime:sender.value];
    }
}
// 当前按钮
- (void)btnCurrentAction:(id)sender
{
    if (self.player.state == STKAudioPlayerStatePaused) {
        NSLog(@"播放");
        [self.btnCurrent setImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
        [self.player resume];
    }else if (self.player.state == STKAudioPlayerStatePlaying) {
        NSLog(@"暂停");
        [self.btnCurrent setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        [self.player pause];
    }else
    {
        [self playMusic:self.playUrl];
    }
}
// 上一曲
- (void)btnUpAction:(id)sender
{
        self.indexRow--;
    if (self.indexRow < 0) {
        self.indexRow = self.array_current.count - 1;
    }
    SongList *songList = self.array_current[self.indexRow];
    [self playMusic:songList.song_play_url];
    [self.btnCurrent setImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
    self.labelTitle.text = [self.array_current[self.indexRow] song_name];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Song"];
    request.predicate = [NSPredicate predicateWithFormat:@"songName = %@",self.labelTitle.text];
    NSArray *arrayd = [self.coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    if (arrayd.count > 0) {
        [self.btn_save setImage:[UIImage imageNamed:@"iconfont-shoucangyishoucang"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:self.labelTitle.text];
    }else
    {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:self.labelTitle.text];
        [self.btn_save setImage:[UIImage imageNamed:@"iconfont-shoucangweishoucang-2"] forState:UIControlStateNormal];
    }
}
// 下一曲
- (void)btnNextAction:(id)sender
{
    self.indexRow++;
    if (self.indexRow == self.array_current.count) {
        self.indexRow = 0;
    }
    SongList *songList = self.array_current[self.indexRow];
    [self playMusic:songList.song_play_url];

    [self.btnCurrent setImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
     self.labelTitle.text = [self.array_current[self.indexRow] song_name];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Song"];
    request.predicate = [NSPredicate predicateWithFormat:@"songName = %@",self.labelTitle.text];
    NSArray *arrayd = [self.coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    if (arrayd.count > 0) {
        [self.btn_save setImage:[UIImage imageNamed:@"iconfont-shoucangyishoucang"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:self.labelTitle.text];
    }else
    {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:self.labelTitle.text];
        [self.btn_save setImage:[UIImage imageNamed:@"iconfont-shoucangweishoucang-2"] forState:UIControlStateNormal];
    }
}
// set方法 判断是否为当前的歌曲
- (void)setPlayUrl:(NSString *)playUrl
{
    if (_playUrl != playUrl) {
        _playUrl = playUrl;
        [self playMusic:playUrl];
    }
}

- (void)btnBackAction:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
// 单例
+ (LGCLastViewController *)shareLastViewController
{
    static LGCLastViewController *lastViewController = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        lastViewController = [[LGCLastViewController alloc] init];
    });
    return lastViewController;
}
/***************** 歌曲播放状态  *****************/
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    NSLog(@"下一曲");
}
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didCancelQueuedItems:(NSArray *)queuedItems
{
    NSLog(@"2");
}
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId
{
    NSLog(@"3");
}
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer logInfo:(NSString *)line
{
    NSLog(@"4");
}
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId
{
    NSLog(@"5");
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    NSLog(@"6");
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    NSLog(@"7");
}
/***************** 下载 *****************/

- (void)btn_downloadAction:(UIButton *)sender
{
    MBProgressHUD *MBP = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [MBP show:YES];
    MBP.mode = MBProgressHUDModeText;
    MBP.labelText = @"正在下载";
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBP removeFromSuperview];
    });
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        // 创建请求对象
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.playUrl]];
        // 设置请求参数, 字节
        NSString *rang = [NSString stringWithFormat:@"byte:%f",_current];
        [request setValue:rang forHTTPHeaderField:@"Range"];
        // 建立连接
        self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
        // 开始请求
        [self.connection start];
    }else{
        [self.connection cancel];
    }
}
// 收到响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 获取总文件大小
    self.total = response.expectedContentLength;
    // 创建文件管理器
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *cachesPath  = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [cachesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",self.labelTitle.text]];
    // 创建文件
    [manager createFileAtPath:filePath contents:nil attributes:nil];
    // 打开一个文件用于写入
    self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
    // 计算当前总大小 length
    _current += data.length;
    // 更新进度条
    [self.fileHandle seekToEndOfFile];
    [self.fileHandle writeData:data];
}
// 下载
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    MBProgressHUD *MBP = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [MBP show:YES];
    MBP.mode = MBProgressHUDModeText;
    MBP.labelText = @"下载完成";
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBP removeFromSuperview];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
